package com.project.market.controller;

import com.project.market.db.domain.MarketStorage;
import com.project.market.service.AdminStorageService;
import com.project.market.service.impl.AdminStorageServiceImpl;
import com.project.market.util.JacksonUtil;
import com.project.market.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;
@MultipartConfig
@WebServlet("/admin/storage/*")
public class AdminStorageController extends HttpServlet {

    AdminStorageService adminStorageService = new AdminStorageServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String op = req.getRequestURI().replace(req.getContextPath() + "/admin/storage/", "");
        if("create".equals(op)) {
            create(req,resp);
        }
    }

    private void create(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part part = req.getPart("file");
        String fileName = part.getSubmittedFileName();
        long size = part.getSize();
        String contentType = part.getContentType();
        String suffix = fileName.substring(fileName.indexOf("."));
        String key = UUID.randomUUID().toString() + suffix;
        File file = new File("D:/app/" + key);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        part.write(file.getAbsolutePath());

        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setDeleted(false);
        marketStorage.setUrl("/wx/storage/fetch/"+key);
        marketStorage.setAddTime(LocalDateTime.now());
        marketStorage.setUpdateTime(LocalDateTime.now());
        marketStorage.setType(contentType);
        marketStorage.setSize((int) size);
        marketStorage.setName(fileName);
        marketStorage.setKey(key);

        adminStorageService.insert(marketStorage);
        marketStorage.setUrl("http://localhost:8083/"+marketStorage.getUrl());
        Object ok = ResponseUtil.ok(marketStorage);
        String s = JacksonUtil.writeValueAsString(ok);
        resp.getWriter().println(s);
    }
}
